package com.xxkj.orcfx.utils;

/**
 * Base64编解码
 *
 * @author 513416
 *
 */
public class Base64 {

	/**
     * @param bytes
     * @return
     */
    public static byte[] decode(final byte[] bytes) {
        return org.apache.commons.codec.binary.Base64.decodeBase64(bytes);
    }


    public static byte[] decode(String str) {
    	return decode(str.getBytes());
    }

    /**
     *
     * <br>解析成字符串</br>
     *
     * @author    515120
     * @email     yusai@dafycredit.com
     * @date      2017年11月17日 下午5:54:09
     * @version   1.0
     * @since     1.0
     * @param byteStr
     * @return
     */
    public static String decodeToString(String str){
        String decodeString=new String(decode(str));
        return decodeString;
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(final byte[] bytes) {
        return new String(org.apache.commons.codec.binary.Base64.encodeBase64(bytes));
    }


    public static String safeUrlBase64Encode(byte[] data){
        String encodeBase64 = encode(data);
        String safeBase64Str = encodeBase64.replace('+', '-');
        safeBase64Str = safeBase64Str.replace('/', '_');
        safeBase64Str = safeBase64Str.replaceAll("=", "");
        return safeBase64Str;
    }

    public static String safeUrlBase64Decode(final String safeBase64Str){
        String base64Str = safeBase64Str.replace('-', '+');
        base64Str = base64Str.replace('_', '/');
        int mod4 = base64Str.length()%4;
        if(mod4 > 0){
            base64Str = base64Str + "====".substring(mod4);
        }
        return base64Str;
    }

    public static void main(String[] args) {
        String test = "abc";
        String test64 = Base64.encode(test.getBytes());
        System.out.println(test64);
        System.out.println(Base64.decode(test64));
        System.out.println(Base64.decodeToString(test64));
	}



}
